<template>
    <div class="question-box">
        <div class="question-item">
            <div class="question-system">
                <div class="left-menu">
                    <div class="category-list">
                        <div class="category-item active">
                            <img src="@/assets/cate.png" alt="">
                            <span>默认分类(2)</span>
                            <span class="el-icon-arrow-right"></span>
                        </div>
                    </div>
                </div>
                <div class="right-content">
                    <div class="search-area">
                        <div class="search-row">
                            <el-input v-model="searchParams.questionStem" placeholder="请输入题干信息"></el-input>
                            <el-input v-model="searchParams.exerciseNo" placeholder="请输入习题编号"></el-input>
                            <el-select v-model="searchParams.type" placeholder="请选择类型" style="width: 100%">
                                <el-option label="单选题" value="0"></el-option>
                                <el-option label="多选题" value="1"></el-option>
                            </el-select>
                            <el-select v-model="searchParams.difficulty" placeholder="请选择难易度" style="width: 100%">
                                <el-option label="简单" value="easy"></el-option>
                                <el-option label="中等" value="medium"></el-option>
                                <el-option label="困难" value="hard"></el-option>
                            </el-select>
                            <el-select v-model="searchParams.status" placeholder="请选择习题状态" style="width: 100%">
                                <el-option label="已发布" value="published"></el-option>
                                <el-option label="草稿" value="draft"></el-option>
                            </el-select>
                        </div>
                        <div class="search-actions">
                            <div class="lefts">
                                <div class="items">
                                    <div class="btn-primary" @click="questionAdd = true">
                                        <img src="@/assets/add-point.png" alt="">
                                        <span>习题库添加</span>
                                    </div>
                                </div>
                                <div class="items">
                                    <div class="btn-primary" @click="importDialogVisable = true">
                                        <img src="@/assets/import.png" alt="">
                                        <span>导入</span>
                                    </div>
                                </div>
                                <div class="items">
                                    <div class="btn-primary">
                                        <img src="@/assets/out.png" alt="">
                                        <span>导出</span>
                                    </div>
                                </div>
                            </div>
                            <div class="items">
                                <el-button @click="reset">
                                    <el-icon>
                                        <RefreshLeft />
                                    </el-icon>重置
                                </el-button>
                                <el-button @click="listPage">
                                    <el-icon>
                                        <Search />
                                    </el-icon>查询
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <div class="table-area">
                        <el-table ref="multipleTableRef" :data="questions" style="width: 100%"
                            @selection-change="handleSelectionChange">
                            <el-table-column type="selection" />
                            <el-table-column prop="questionStem" label="题干信息" width="150">
                                <template #default="scope">
                                    <el-tooltip class="box-item" effect="dark" :content="scope.row.questionStem"
                                        placement="top-start">
                                        <div class="text" v-html="scope.row.questionStem"></div>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column prop="exerciseNo" label="习题编号" />
                            <el-table-column label="习题类型">
                                <template #default="scope">
                                    {{ scope.row.type === '0' ? '单选题' : '多选题' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="difficulty" label="难易度" >
                                <template #default="scope">
                                <span v-if="scope.row.difficulty === 'easy'">简单</span>
                                <span v-if="scope.row.difficulty === 'medium'">中等</span>
                                <span v-else>困难</span>
                            </template>
                            </el-table-column>
                            <el-table-column prop="uploader" label="上传人" />
                            <el-table-column prop="createTime" label="上传时间" :formatter="dateFormat"/>
                            <el-table-column property="name" label="操作" width="200">
                                <template #default="scope">
                                    <div class="material-operations">
                                        <el-link type="primary" @click="showMaterial(scope.row.id)"
                                            underline="false">预览</el-link>
                                        <el-link type="success" @click="editMaterial(scope.row.id)"
                                            underline="false">编辑</el-link>
                                        <el-link type="warning" @click="deleteMaterial(scope.row.id)"
                                            underline="false">删除</el-link>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="pages">
                            <el-pagination small background layout="prev, pager, next" :total="questions.length"
                                class="mt-4" v-model:current-page="searchParams.pageNum" @current-change="exerciseList"/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog v-model="questionShow" width="50%" height="600px" top="15vh">
            <template #header>
                <div class="headers">
                    <span>习题预览</span>
                </div>
            </template>
            <div class="exercise-preview">
                <div class="knowledge-point">
                    <span class="knowledge-label">所属知识点：</span>
                    {{questionData.knowledgePoint}}
                </div>

                <div class="question-container">
                    <div class="question-header">
                        <div class="question-type">{{ questionData.type }}</div>
                        <div class="question-text" v-html="questionData.text "></div>
                    </div>
                    <div class="options-list">
                        <div v-for="(option, index) in questionData.options" :key="index" class="option-item"
                            :class="{ selected: optionSele == index }" @click="optionSelect(index)">
                            <div class="left">
                                <span class="option-letter">{{ option.optionCode }}</span>
                                <span class="option-text">{{ option.optionContent }}</span>
                            </div>
                            <span class="radio-button"></span>
                        </div>
                    </div>
                </div>

                <div class="answer-section">
                    <div class="correct-answer">正确答案：{{ questionData.correctAnswer }}</div>
                    <div class="analysis-text">{{ questionData.analysis }}</div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="questionShow = false"> 取消 </el-button>
                    <el-button type="primary" @click="questionShow = false"> 确认 </el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="questionAdd" width="50%" height="600px" top="15vh">
            <template #header>
                <div class="headers">
                    <span>新建习题</span>
                </div>
            </template>
            <div class="exercise-preview">
                <div class="form-item">
                    <div class="item-label">习题类型：</div>
                    <el-radio-group v-model="types" @change="typeSelect">
                        <el-radio-button label="单选题" />
                        <el-radio-button label="填空题" />
                    </el-radio-group>
                </div>
                <div class="form-item editors">
                    <div class="item-label">题干信息：</div>
                    <div class="tips" v-show="types == '填空题'">提示：在题干中，使用（）来表示需要填空的位置，例如："敏捷开发更注重（）和（），而非详尽的文档。""</div>
                    <div class="items">
                        <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor class="custom-editor" v-model="addParams.exercise.questionStem"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </div>
                <div class="form-item" v-show="types == '单选题'">
                    <div class="btn-primary" @click="addOptions">
                        <img src="@/assets/add-point.png" alt="">
                        <span>添加选项</span>
                    </div>
                </div>
                <div class="form-item" v-show="types == '单选题'">
                    <div v-if="optionShow" class="answer-options">
                        <div class="answeritem" v-for="(item, index) in optionsAnswer" :key="item.optionCode">
                            <div class="options">{{ item.optionCode }}</div>
                            <el-input v-model="item.optionContent" placeholder="请输入选项内容"></el-input>
                            <div class="options-btn" @click="deleOptions(index)">
                                <img src="@/assets/dele.png" alt="">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-item" v-show="types == '填空题'">
                    <div class="btn-primary" @click="addFillOptions">
                        <img src="@/assets/add-point.png" alt="">
                        <span>答案选项</span>
                    </div>
                </div>
                <div class="form-item" v-show="types == '填空题'">
                    <div v-if="fillAnswer.length > 0" class="answer-options">
                        <div class="answeritem" v-for="(item,index) in fillAnswer" :key="item">
                            <div class="answerlabel">第{{ item.optionCode}}空</div>
                            <el-input v-model="item.optionContent" placeholder="请输入选项内容"></el-input>
                            <div class="options-btn" @click="deleOptions(index)">
                                <img src="@/assets/dele.png" alt="">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-item">
                    <div class="item-label">难易程度：</div>
                    <el-select v-model="addParams.exercise.difficulty" placeholder="请选择难易程度">
                        <el-option label="简单" value="easy" />
                        <el-option label="中等" value="medium" />
                        <el-option label="困难" value="hard" />
                    </el-select>
                </div>
                <div class="form-item">
                    <div class="item-label">习题分类：</div>
                    <el-select v-model="question_cate" placeholder="请选择习题分类">
                        <el-option label="默认分类" value="默认分类" />
                    </el-select>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="questionAdd = false"> 取消 </el-button>
                    <el-button type="primary" @click="addExercise"> 保存 </el-button>
                    <el-button type="primary" @click="addExerciseAndBuild"> 保存并创建下一习题 </el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="importDialogVisable" title="Tips" width="35%" top="25vh">
            <template #header>
                <div class="my-header">
                    <span>导入习题</span>
                </div>
            </template>
            <div class="exercise-preview">
                <div class="add-form">
                    <div class="form-item">
                        <div class="items">
                            <div class="text">下载模板：</div>
                            <el-link type="primary">点击下载批量导入模板</el-link>
                        </div>
                    </div>
                </div>
                <div class="add-form">
                    <div class="form-item">
                        <div class="items">
                            <div class="text">上传模板：</div>
                            <el-upload ref="uploadRef" class="upload-demo"
                                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                                :auto-upload="false" :on-change="handleFileChange" :show-file-list="false"
                                :multiple="false">
                                <template #trigger>
                                    <el-button type="primary">点击上传</el-button>
                                </template>
                            </el-upload>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="importDialogVisable = false">上传</el-button>
                    <el-button @click="importDialogVisable = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, shallowRef } from 'vue'
import { RefreshLeft, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import api from '@/api/index'

const searchParams = ref({ questionStem: '', exerciseNo: '', type: '', difficulty: '', status: '', pageNum: 1, pageSize: 10 });
const addParams = ref({ exercise: { type: '', questionStem: '', difficulty: '',uploader:'' }, optionList: [] })
const questions = ref([
]);
const questionShow = ref(false);
const questionAdd = ref(false);
const optionShow = ref(false);
const importDialogVisable = ref(false);
const questionType = ref(0);
const types = ref("单选题");
const question_cate = ref("默认分类");
const questionData = ref({
    knowledgePoint: '知识点内容占位',
    type: '单选',
    text: '题目文本内容占位',
    options: [
    ],
    correctAnswer: 'B',
    analysis: '解析内容占位'
});
const optionSele = ref(0);
const fillAnswer = ref([]);
const editorRef = shallowRef();
const optionsTxt = ref(["A", "B", "C", "D", "E"]);
const optionsAnswer = ref([]);

const toolbarConfig = {
    excludeKeys: ["uploadVideo", "fullScreen"],
};
const editorConfig = ref({
    placeholder: "请输入内容详情...",
    MENU_CONF: {}
});
 const dateFormat = (row)=>{
      const date = new Date(row.createTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
 }

const handleCreated = (editor) => {
    editorRef.value = editor;
};
const optionSelect = (e) => {
    optionSele.value = e
};
const typeSelect = () => {
    questionType.value = types.value == "单选题" ? 0 : 1;
    addParams.value.exercise.type = types.value == "单选题" ? 0 : 1;
};
const addOptions = () => {
    if (!optionShow.value) {
        optionShow.value = true;
        optionsAnswer.value = [{ optionCode: optionsTxt.value[0], optionContent: "" }];
    } else {
        var key = optionsAnswer.value.length
        if (key >= 5) {
            ElMessage({ type: 'error', message: '最多只能添加5个选项', })
            return;
        } else {
            optionsAnswer.value = [
                ...optionsAnswer.value,
                { optionCode: optionsTxt.value[key], optionContent: "" }
            ]
        }
    }
};
const deleOptions = (index) => {
    optionsAnswer.value.splice(index, 1);
    for (var i = 0; i < optionsAnswer.value.length; i++) {
        optionsAnswer.value[i] = optionsTxt.value[i]
    }
};
const addFillOptions = () => {
    var key = fillAnswer.value.length
    fillAnswer.value.push({ optionCode: key + 1, optionContent: "" })
};

const exerciseList = async () => {
    let res = await api.exercise_page(searchParams.value)
    questions.value = res.list
};
exerciseList();

const listPage = () => {
    searchParams.value.pageNum = 1
    exerciseList();
};

const reset = () => {
    searchParams.value = { questionStem: '', exerciseNo: '', type: '', difficulty: '', status: '', pageNum: 1, pageSize: 10 };
    exerciseList();
};

const addExercise = async () => {
    if(addParams.value.exercise.type === 0){
        addParams.value.optionList = optionsAnswer.value
    }else{
        addParams.value.optionList = fillAnswer.value
    }
    addParams.value.exercise.uploader =  JSON.parse(localStorage.getItem("user")).name;
    let res = await api.exercise_addExercise(addParams.value)
    if (res.code === -1) {
        ElMessage.error(res.data)
        return
    }
    questionAdd.value = false
    listPage()
};

const addExerciseAndBuild = async () => {
    await api.exercise_add(addParams.value)
    questionAdd.value = true
    initAddParams()
    listPage()
};

const initAddParams = () => {
    addParams.value = {exercise: { type: '', questionStem: '', difficulty: '',uploader:'' }, optionList: [] }
    optionsAnswer.value = []
    fillAnswer.value = []
}

const showMaterial = async (id) => {
    questionShow.value = true
    const res = await api.exercise_detail({ id })
    let type = res.data.exercise.type
    if(type=== "0"){
        questionData.value.type = '单选'
       
    }else{
         questionData.value.type = '多选'
    }
    questionData.value.text = res.data.exercise.questionStem
    questionData.value.options= res.data.optionList
};

const editMaterial = async (id) => {
    questionAdd.value = true
    const res = await api.exercise_detail({ id })
    addParams.value.exercise = res.data.exercise
    addParams.value.optionList = res.data.optionList
    if(res.data.exercise.type === "0"){
        optionsAnswer.value = res.data.optionList
    }else{
         fillAnswer.value = res.data.optionList
    }
};

const deleteMaterial = (id) => {
    ElMessageBox.confirm('确定要删除吗？', '确认删除？', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', }).then(() => {
        api.exercise_delete({ id })
        ElMessage({ type: 'success', message: 'Delete completed', })
        listPage()
    }).catch(() => {
        ElMessage({ type: 'info', message: 'Delete canceled', })
    })
};
</script>
<style scoped>
:deep(.el-scrollbar__view) {
    height: 100%;
}

:deep(.is-active .el-radio-button__inner) {
    background-color: #1465E1 !important;
    border: 1px solid #1465E1 !important;
}

.question-box {
    position: relative;
}

.question-item {
    width: 100%;
    background: #fff;
    border-radius: 8px;
}

.question-system {
    display: flex;
    padding: 30px;
    gap: 30px;
}

.left-menu {
    width: 250px;
    background: white;
    overflow: hidden;
    border-radius: 8px;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.15);
    border-radius: 20px;
    min-height: calc(85vh - 50px);
}

.category-list {
    margin-top: 30px;
}

.category-item {
    width: 100%;
    margin-bottom: 8px;
    cursor: pointer;
    display: flex;
    justify-content: start;
    align-items: center;
    padding: 10px;
    gap: 5px;
}

.category-item img {
    width: 20px;
}

.category-item.active {
    background-color: #ecf5ff;
}

.category-item:hover {
    background-color: #f5f7fa;
}

.right-content {
    width: 100%;
    height: calc(85vh - 50px);
}

.search-area {
    height: 100px;
}

.search-row {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
    justify-content: space-between;
    flex-direction: row;
}

.search-actions {
    display: flex;
    flex-direction: row;
    gap: 10px;
    justify-content: space-between;
    padding-bottom: 10px;
}

.search-actions .lefts {
    display: flex;
    flex-direction: row;
    gap: 10px;
}

.table-area {
    background: white;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    height: calc(85vh - 200px);
    position: relative;
}

.table-area .text {
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
}

.material-operations {
    display: flex;
    justify-content: space-around;
}

.operation-preview {
    width: 50px;
    cursor: pointer;
}

.pages {
    display: flex;
    flex-direction: row;
    justify-content: end;
    padding-top: 30px;
    position: absolute;
    bottom: 20px;
    right: 20px;
}

.headers {
    text-align: left;
}

.exercise-preview {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    gap: 10px;
    display: flex;
    flex-direction: column;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eaeef2;
}

.preview-title {
    font-size: 18px;
    font-weight: 600;
    color: #1f2f3d;
}

.question-header {
    display: flex;
    gap: 5px;
    align-items: center;
    margin-bottom: 10px;
}

.knowledge-point {
    padding: 10px;
    border-bottom: 1px solid #eaeef2;
    color: #606266;
    text-align: left;
}

.knowledge-label {
    font-weight: 500;
    margin-right: 8px;
    color: #303133;
}

.question-container {
    padding: 20px;
}

.question-type {
    display: inline-block;
    padding: 4px 15px 4px 15px;
    background: #1465E1;
    color: white;
    border-radius: 50px;
    font-size: 12px;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
}

.question-text {
    font-size: 14px;
    color: #303133;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
}

.options-list {
    display: grid;
    gap: 12px;
}

.option-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background: #f5f7fa;
    border-radius: 8px;
    border: 1px solid #eaeef2;
}

.option-letter {
    font-weight: 500;
    margin-right: 12px;
    color: #606266;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
}

.option-text {
    color: #303133;
}

.radio-button {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    border: 1px solid #dcdfe6;
    position: relative;
    margin-left: 10px;
}

.selected .radio-button {
    border-color: #1465E1;
    background: #1465E1;
}

.selected .radio-button::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: white;
}

.answer-section {
    padding: 20px;
    background: #f9fafc;
    border-top: 1px solid #eaeef2;
}

.correct-answer {
    color: #1465E1;
    font-weight: 500;
    margin-bottom: 12px;
    text-align: left;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
}

.analysis-text {
    color: #606266;
    text-align: left;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
}

.btn-primary {
    background: #1465E1;
    color: white;
    padding: 5px 20px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    gap: 5px;
    border-radius: 4px;
    cursor: pointer;
}

.btn-primary img {
    width: 18px;
}

.btn-primary span {
    font-size: 14px;
    ;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
}

.editors {
    flex-direction: column;
    align-items: start;
}

.editors .item-label {
    flex: 0 0 20px;
}

.my-header {
    text-align: left;
}

.form-item {
    display: flex;
    flex-direction: row;
    justify-content: start;
    gap: 10px;
    align-items: center;
}

:deep(.custom-editor .w-e-text-container) {
    border: 1px solid #dcdfe6 !important;
    min-height: 200px;
    text-align: left;
}

.item-label {
    flex: 0 0 80px;
    text-align: left;
    height: 35px
}

.answer-options {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.answeritem {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    gap: 10px;
}

.answeritem .options {
    width: 25px;
    height: 25px;
    border-radius: 25px;
    background: #1465E1;
    color: #fff;
    font-size: 12px;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
    line-height: 25px;
}

:deep(.answeritem .el-input) {
    width: calc(100% - 20px);
}

.options-btn {
    width: 20px;
    height: 20px;
    cursor: pointer;
}

.options-btn img {
    width: 20px;
    height: 20px;
}

.tips {
    color: #D49C1F;
    font-size: 12px;
    font-family: 微软雅黑, Microsoft YaHei, SimSun;
}

.answerlabel {
    flex: 0 0 50px;
}

.add-form {
    width: calc(100% - 30px);
    margin: 10px auto;
    display: flex;
    flex-direction: row;
    gap: 20px;
}

.form-item {
    flex: 1;
}

.add-form .items {
    display: flex;
    flex-direction: row;
    gap: 5px;
    align-items: center;
}

.add-form .items .reds {
    color: red;
}

.add-form .inputs {
    margin-top: 10px;
}
</style>